#!/usr/bin/python
# -*- coding: utf-8 -*-


import datetime
import os
import sys
import getopt
#import threading

from ssh import sshCommand,sshUploadFile
from sshThread import SshTread

def info():
    """
    程序说明
    """
    print "version:1.0.0"
    print "author:sftang"
    print "ssh命令操作,文件上传"

def usage():
    """
    使用说明
    """
    print "Usage:"
    print "    python %s -t type -l localfile -h host -u username -p passwd" % sys.argv[0]
    print "\t-t\t\t上传文件方式"
    print "\t\t\tcmd:执行命令,file:自定义远程保存文件"
    print "\t-l\t\t本地上传文件"
    print "\t-r\t\t远程保存文件,如果不写表示同本地目录文件名"
    print "\t-h\t\t主机IP"
    print "\t-P\t\t端口 default = 22"
    print "\t-u\t\t用户名 defult = root"
    print "\t-p\t\t密码 default = %TGB^YHN"
    print "\t-k\t\t密钥文件"
    print "\t--file\t\t要上传的文件列表"
    print "\t--cmd\t\t执行命令,使用;间隔,如 free;df -h"
    print "\t--hostfile\t主机列表文件,格式 ip:port:username:passwd"
    print "\t--help\t\t帮助说明"
    print "\t--version\t版本说明"


if __name__ == '__main__':

    #判断参数至少有一个
    if len(sys.argv) <=1:
        print "\033[31;1m[Error]===>请指定参数\033[0m"
        usage()
        sys.exit(0)

    #输入参数错误引起的异常
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:l:r:h:P:u:p:k:',
                                   ["help","version","hostfile=","cmd=","file="])
    except getopt.GetoptError,e:
        print "\033[31;1m[Error]===>",e,"\033[0m"
        usage()
        sys.exit(0)

    cmd = None
    exec_type = None
    local_file = None
    remote_file = None
    filelist = None
    host = None
    port = 22
    username = 'root'
    passwd = '%TGB^YHN'
    key = None
    hostfile = None

    for op, value in opts:
        if op == '-t':
            exec_type = value
        elif op == '--cmd':
            cmd = value
        elif op == '-l':
            local_file = value
        elif op == '-r':
            remote_file = value
        elif op == '--file':
            filelist = value
        elif op == '-h':
            host = value
        elif op == '-P':
            port = value
        elif op == '-u':
            username = value
        elif op == '-p':
            passwd = value
        elif op == '-k':
            key = value
            print "未实现 :)"
            sys.exit(0)
        elif op == '--hostfile':
            hostfile = value
        elif op == '--help':
            usage()
            sys.exit(0)
        elif op == '--version':
            info()
            sys.exit(0)

    if not exec_type:
        print "\033[31;1m[Error]===>必须指定类型,使用--help查看帮助\033[0m"
        sys.exit(0)

    if not host and not hostfile:
        print "\033[31;1m[Error]===>必须指定远程主机或主机列表文件,使用--help查看帮助\033[0m"
        sys.exit(0)

    if exec_type == 'cmd':
        if not cmd:
            print "\033[31;1m[Error]===>必须指定需要执行的命令,使用--help查看帮助\033[0m"
            sys.exit(0)

        if not hostfile:
            sshCommand(host,cmd = cmd, username = username,password = passwd,port = port)
        else:
            try:
                f = open(hostfile).readlines()
                for line in f:
                    
                    #忽略开头是井号的
                    if line[0] == '#' or len(line.strip()) == 0:
                        continue
                    
                    #去掉空格
                    host,port,username,passwd = line.strip().split(':')

                    task = SshTread("Thread_"+host,host,cmd = cmd, exec_type = exec_type, 
                                    username = username,password = passwd,port=int(port))
                    task.start()

            except IOError,e:
                #文件打开失败
                print "\033[31;1m [Error]===>%s \033[0m" % e        
    else:
        if not local_file and not filelist:
            print "\033[31;1m[Error]===>必须指定本地文件或者列表文件,使用--help查看帮助\033[0m"
            sys.exit(0)

        if not hostfile:
            sshUploadFile(host,local_file = local_file,remote_file = remote_file,filelist=filelist,
                          username = username,password = passwd,port = port)
        else:
            try:
                f = open(hostfile).readlines()
                for line in f:
                    
                    #忽略开头是井号的
                    if line[0] == '#' or len(line.strip()) == 0:
                        continue
                    
                    #去掉空格
                    host,port,username,passwd = line.strip().split(':')

                    task = SshTread("Thread_"+host,host,local_file = local_file,remote_file = remote_file,
                                    exec_type = exec_type,username=username,password=passwd,port=int(port),
                                    filelist=filelist)
                    task.start()

            except IOError,e:
                #文件打开失败
                print "\033[31;1m [Error]===>%s \033[0m" % e

    
    
    #直接使用threading
    #if exec_type == 'cmd':
        #if not cmd:
            #print "\033[31;1m[Error]===>必须指定需要执行的命令,使用--help查看帮助\033[0m"
            #sys.exit(0)

        #sshCommand(host,cmd = cmd, username = username,password = passwd,port = port)
    #else:
        #if not local_file and not filelist:
            #print "\033[31;1m[Error]===>必须指定本地文件或者列表文件,使用--help查看帮助\033[0m"
            #sys.exit(0)

        #if not hostfile:
            #sshUploadFile(host,local_file,remote_file,
                          #username = username,password = passwd,port = port)
        #else:
            #try:
                #f = open(hostfile).readlines()
                #for line in f:
                    ##去掉空格
                    #host,port,username,passwd = line.strip().split(':')

                    #task =threading.Thread(target=sshUploadFile(host,local_file,remote_file,
                                                 #username=username,
                                                 #password = passwd,
                                                 #port = int(port)))
                    #task.start() 

            #except IOError,e:
                ##文件打开失败
                #print "\033[31;1m [Error]===>%s \033[0m" % e
